/*
 * @Author: wangjh wangjiahui0710@163.com
 * @Date: 2024-06-18 10:06:27
 * @LastEditors: wangjh wangjiahui0710@163.com
 * @LastEditTime: 2024-06-19 09:18:31
 * @FilePath: \cip-admin\src\stores\company.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { whManagerBsTbEnterpriseGetByIdIdUsingPost } from "@/genapi/wh";

import { useUserStore } from "./user";

/**
 * 当前用户企业信息
 */
export const useCompanyStore = defineStore("company", () => {
	const userStore = useUserStore();

	const { state: companyInfo, execute: refresh } = useAsyncState(
		async () => {
			if (userStore.userInfo?.systemUser?.relatedId) {
				const companyId = userStore.userInfo?.systemUser?.relatedId ?? "";
				const { data } = await whManagerBsTbEnterpriseGetByIdIdUsingPost({
					path: { id: companyId },
				});
				return data;
			}
		},
		undefined,
		{
			immediate: false,
		},
	);

	watchImmediate(
		() => userStore.userInfo?.systemUser?.relatedId,
		() => refresh(),
	);

	const currentCompanyId = computed(() => companyInfo.value?.id);

	return {
		companyInfo: readonly(companyInfo),
		currentCompanyId,
		refresh,
	};
});
